package org.one.onecat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.one.disruptor.MessageProducer;
import org.one.disruptor.RingBufferWorkerPoolFactory;
import org.one.entity.TranslatorDataWrapper;
import org.one.servlet.OneServlet;

import java.util.Map;

/**
 * @Classname : OneCatHandler
 * @Description : netty读取处理器
 * @Author : cty
 * @Date 2023/6/11 22:24
 */


public class OneCatHandler extends ChannelInboundHandlerAdapter {

    private final Map<String, String> nameToClassNameMap;
    private final Map<String, OneServlet> nameToServletMap;

    public OneCatHandler(Map<String, String> nameToClassNameMap, Map<String, OneServlet> nameToServletMap) {
        this.nameToClassNameMap = nameToClassNameMap;
        this.nameToServletMap = nameToServletMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        TranslatorDataWrapper wrapper = new TranslatorDataWrapper();
        wrapper.setMsg(msg);
        wrapper.setCtx(ctx);
        wrapper.setNameToClassNameMap(this.nameToClassNameMap);
        wrapper.setNameToServletMap(this.nameToServletMap);
        // 读取数据后暂不处理，而是发布到高性能队列中
        String producerId = "onecat:producer:" + Thread.currentThread().getName();
        MessageProducer messageProducer = RingBufferWorkerPoolFactory.getInstance().getMessageProducer(producerId);
        messageProducer.setData(wrapper);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
